package com.ruoyi.framework.config.third;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

//@Component
public class GithubAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private GithubClientService githubClientService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        GithubAuthenticationToken token = (GithubAuthenticationToken) authentication;
        String accessToken = (String)token.getPrincipal();
        //根据accessToken 获取github用户信息
        Map<String, Object> userInfo = githubClientService.queryUser(accessToken);
        //然后，根据github用户，查询对应系统用户信息
        UserDetails user = userDetailsService.loadUserByUsername("admin");
        if (Objects.isNull(user)) {
            throw new InternalAuthenticationServiceException("根据accessToken：" + accessToken + "，无法获取对应的用户信息！");
        }
        UsernamePasswordAuthenticationToken authenticationResult = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getAuthorities());
        authenticationResult.setDetails(token.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return GithubAuthenticationToken.class.isAssignableFrom(authentication);
    }
}